<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>关键人员导入</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei';
            background-color: #f5f5f5;
            overflow-x: hidden;
        }

        .container {
            min-height: 100vh;
            display: flex;
            padding: 10px;
            box-sizing: border-box;
        }

        .main-panel {
            width: 100%;
            display: flex;
            flex-direction: column;
        }

        .toolbar-section {
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            background-color: #ffffff;
            flex-shrink: 0;
        }

        .table-section {
            flex: 1;
            padding: 10px;
            box-sizing: border-box;
            overflow: auto;
            min-height: 0;
            margin-top: 10px;
            background-color: #ffffff;
        }

        .upload-section {
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin: 20px;
            text-align: center;
        }

        .upload-btn {
            margin: 20px 0;
        }

        .file-list {
            margin-top: 20px;
            border-top: 1px solid #e9ecef;
            padding-top: 20px;
        }

        .file-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px dashed #e9ecef;
        }

        .file-name {
            color: #2c3e50;
        }

        .file-actions {
            display: flex;
            gap: 10px;
        }

        .import-progress {
            margin-top: 20px;
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 4px;
        }

        .error-message {
            margin-top: 20px;
            padding: 10px;
            background-color: #fff;
            border-radius: 4px;
        }

        .dialog-footer {
            text-align: right;
            padding: 10px 20px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">
            <div class="main-panel">

                <div class="toolbar-section">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <h3>关键人员管理</h3>
                        <div>
                            <el-button type="primary" size="small" @click="openImportDialog">导入数据</el-button>
                            <el-button type="success" size="small" @click="openAddDialog">新增人员</el-button>
                        </div>
                    </div>
                </div>

                <div class="table-section">
                    <!-- 数据展示区域 -->
                    <el-table :data="tableData" ref="table" style="width: 100%;" border stripe
                        :height="tableMaxHeight()">
                        <el-table-column prop="employeeName" label="姓名" min-width="120"
                            align="center"></el-table-column>
                        <el-table-column prop="employeeCode" label="工号" min-width="100"
                            align="center"></el-table-column>
                        <el-table-column prop="location" label="Location" min-width="120"
                            align="center"></el-table-column>
                        <el-table-column prop="bu" label="BU" min-width="150" align="center"></el-table-column>
                        <el-table-column prop="remarks" label="备注" min-width="200" align="center"></el-table-column>
                        <el-table-column label="操作" min-width="150" align="center" fixed="right">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
                                <el-button type="text" size="small" style="color: #f56c6c;"
                                    @click="deletePerson(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 分页组件 -->
                    <div style="margin-top: 20px; text-align: center;" v-if="importData.length > 0">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>

        <!-- 导入弹窗 -->
        <el-dialog title="导入关键人员数据" :visible.sync="importDialogVisible" width="500px" :before-close="handleDialogClose">
            <div class="upload-section" style="margin: 0; box-shadow: none;">
                <div class="upload-btn">
                    <el-upload action="" :auto-upload="false" :on-change="handleChange" :on-remove="handleRemove"
                        :limit="1" accept=".xlsx,.xls" drag>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或点击上传</div>
                        <div class="el-upload__tip" slot="tip">支持Excel格式，单个文件大小不超过10MB<br>Excel文件只需包含工号和备注两列</div>
                    </el-upload>
                </div>

                <div v-if="uploadedFiles.length > 0" class="file-list">
                    <div v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
                        <div class="file-name">{{ file.name }}</div>
                        <div class="file-actions">
                            <el-button size="mini" type="danger" @click="removeFile(index)">删除</el-button>
                        </div>
                    </div>
                </div>

                <!-- 导入进度显示 -->
                <div v-if="isProcessing" class="import-progress">
                    <el-progress :percentage="importProgress" status="success"></el-progress>
                    <p style="margin-top: 10px;">正在处理文件...</p>
                </div>

                <!-- 错误信息显示 -->
                <div v-if="errorMessage" class="error-message">
                    <el-alert title="导入错误" :description="errorMessage" type="error" show-icon>
                    </el-alert>
                </div>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closeImportDialog">取 消</el-button>
                <el-button type="primary" @click="startImport" :loading="isProcessing"
                    :disabled="uploadedFiles.length === 0">开始导入</el-button>
            </div>
        </el-dialog>

        <!-- 新增/编辑人员弹窗 -->
        <el-dialog :title="personFormTitle" :visible.sync="personFormDialogVisible" width="600px"
            :before-close="handlePersonFormClose">
            <el-form :model="personForm" :rules="personFormRules" ref="personForm" label-width="120px">
                <el-form-item label="选择人员" prop="userId">
                    <el-select v-model="personForm.userId" filterable placeholder="请选择人员" style="width: 100%;">
                        <el-option v-for="user in userList" :key="user.id" :label="`${user.name} (${user.code})`"
                            :value="user.id">
                            <span style="float: left">{{ user.name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ user.code }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="personForm.remarks" type="textarea" :rows="3" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closePersonFormDialog">取 消</el-button>
                <el-button type="primary" @click="submitPersonForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>

    <!-- 引入Vue.js -->
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <!-- 引入Element UI -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- 引入用户数据 -->
    <script src="user-data.js"></script>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    uploadedFiles: [],
                    importData: [],
                    parsedData: [], // 添加用于存储解析数据的临时变量
                    isProcessing: false,
                    errorMessage: '',
                    tableData: [],
                    currentPage: 1,
                    pageSize: 10,
                    total: 0,
                    importDialogVisible: false,
                    importProgress: 0,
                    // 新增人员表单相关数据
                    personFormDialogVisible: false,
                    isEdit: false,
                    personForm: {
                        id: '',
                        userId: '',
                        remarks: ''
                    },
                    personFormRules: {
                        userId: [{ required: true, message: '请选择人员', trigger: 'change' }]
                    }
                }
            },

            computed: {
                personFormTitle() {
                    return this.isEdit ? '编辑关键人员' : '新增关键人员';
                },
                userList() {
                    return userList || [];
                }
            },

            mounted() {
                // 页面加载时的初始化操作
                window.addEventListener('resize', () => {
                    // 窗口大小改变时重新计算表格高度
                    this.$nextTick(() => {
                        this.$forceUpdate()
                    });
                });
            },

            methods: {
                // 计算表格最大高度，参考department-production-performance.html的实现
                tableMaxHeight() {
                    // 计算表格最大高度：视窗高度 - 工具栏 - 分页组件 - 其他元素
                    const toolbarHeight = 80; // 工具栏高度（固定值）
                    const paginationHeight = 60; // 分页组件高度（固定值）
                    const otherElementsHeight = 60; // padding和margin等其他元素

                    const height = window.innerHeight - toolbarHeight -
                        paginationHeight - otherElementsHeight;

                    console.log(height)
                    return Math.max(height, 300); // 确保最小高度为300px
                },

                // 打开导入弹窗
                openImportDialog() {
                    this.importDialogVisible = true;
                },

                // 关闭导入弹窗
                closeImportDialog() {
                    this.importDialogVisible = false;
                },

                // 处理弹窗关闭
                handleDialogClose(done) {
                    if (this.isProcessing) {
                        this.$message.warning('正在处理文件，请稍后关闭');
                        return;
                    }
                    done();
                },

                // 打开新增人员弹窗
                openAddDialog() {
                    this.isEdit = false;
                    this.personForm = {
                        id: '',
                        userId: '',
                        remarks: ''
                    };
                    this.personFormDialogVisible = true;
                },

                // 打开编辑人员弹窗
                openEditDialog(row) {
                    this.isEdit = true;
                    // 找到对应的用户信息
                    const user = this.userList.find(u => u.id === row.userId) || {};
                    this.personForm = {
                        id: row.id,
                        userId: row.userId,
                        remarks: row.remarks || ''
                    };
                    this.personFormDialogVisible = true;
                },

                // 关闭人员表单弹窗
                closePersonFormDialog() {
                    this.personFormDialogVisible = false;
                },

                // 处理人员表单弹窗关闭
                handlePersonFormClose(done) {
                    this.$refs.personForm.resetFields();
                    done();
                },

                // 提交人员表单
                submitPersonForm() {
                    this.$refs.personForm.validate((valid) => {
                        if (valid) {
                            // 获取选中用户的信息
                            const selectedUser = this.userList.find(user => user.id === this.personForm.userId);

                            if (!selectedUser) {
                                this.$message.error('请选择有效的人员');
                                return;
                            }

                            const personData = {
                                id: this.personForm.id || Date.now().toString(),
                                userId: this.personForm.userId,
                                employeeName: selectedUser.name,
                                employeeCode: selectedUser.code,
                                location: selectedUser.locatiom || '', // 注意：user-data.js中字段名为locatiom
                                bu: selectedUser.bu || '',
                                remarks: this.personForm.remarks || ''
                            };

                            if (this.isEdit) {
                                // 编辑人员信息
                                const index = this.importData.findIndex(item => item.id === this.personForm.id);
                                if (index !== -1) {
                                    // 更新数据
                                    this.importData.splice(index, 1, personData);
                                    this.$message.success('关键人员信息更新成功');
                                }
                            } else {
                                // 检查是否已存在该人员
                                const exists = this.importData.some(item => item.userId === this.personForm.userId);
                                if (exists) {
                                    this.$message.error('该人员已存在于列表中');
                                    return;
                                }

                                // 新增人员信息
                                this.importData.push(personData);
                                this.$message.success('关键人员信息添加成功');
                            }

                            // 更新表格数据
                            this.updateTableData();
                            // 关闭弹窗
                            this.closePersonFormDialog();
                        }
                    });
                },

                // 删除人员
                deletePerson(row) {
                    this.$confirm('此操作将永久删除该人员信息, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const index = this.importData.findIndex(item => item.id === row.id);
                        if (index !== -1) {
                            this.importData.splice(index, 1);
                            this.updateTableData();
                            this.$message.success('人员信息删除成功');
                        }
                    }).catch(() => {
                        // 取消删除
                    });
                },

                handleChange(file, fileList) {
                    this.uploadedFiles = fileList;
                    if (file.raw) {
                        this.parseFile(file.raw);
                    }
                },

                handleRemove(file, fileList) {
                    this.uploadedFiles = fileList;
                },

                removeFile(index) {
                    this.uploadedFiles.splice(index, 1);
                },

                parseFile(file) {
                    // 只支持Excel文件
                    if (file.type.includes('excel') || file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) {
                        this.parseExcel(file);
                    } else {
                        this.$message.error('不支持的文件格式，请上传Excel文件');
                        return;
                    }
                },

                parseExcel(file) {
                    const script = document.createElement('script');
                    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js';
                    script.onload = () => {
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            try {
                                const dataArray = new Uint8Array(e.target.result);
                                const workbook = XLSX.read(dataArray, { type: 'array' });

                                // 获取第一个工作表
                                const firstSheetName = workbook.SheetNames[0];
                                const worksheet = workbook.Sheets[firstSheetName];

                                // 将工作表转换为JSON
                                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                                if (jsonData.length < 2) {
                                    this.$message.error('Excel文件中没有数据');
                                    return;
                                }

                                // 处理表头
                                const headers = jsonData[0];
                                const expectedHeaders = ['工号', '备注'];
                                const headerMap = {};

                                headers.forEach((header, index) => {
                                    const cleanHeader = String(header).trim();
                                    if (expectedHeaders.includes(cleanHeader)) {
                                        headerMap[cleanHeader] = index;
                                    }
                                });

                                // 验证表头是否包含所有必需字段
                                const missingHeaders = expectedHeaders.filter(header => !headerMap.hasOwnProperty(header));
                                if (missingHeaders.length > 0) {
                                    this.$message.error(`缺少必需字段: ${missingHeaders.join(', ')}`);
                                    return;
                                }

                                // 解析数据行
                                const parsedData = [];
                                for (let i = 1; i < jsonData.length; i++) {
                                    const rowArray = jsonData[i];
                                    if (!rowArray || rowArray.length === 0) continue;

                                    // 获取工号和备注
                                    const employeeCodeIndex = headerMap['工号'];
                                    const remarksIndex = headerMap['备注'];

                                    const employeeCode = employeeCodeIndex < rowArray.length ?
                                        String(rowArray[employeeCodeIndex] || '').trim() : '';
                                    const remarks = remarksIndex < rowArray.length ?
                                        String(rowArray[remarksIndex] || '').trim() : '';

                                    // 根据工号查找用户信息
                                    const user = this.userList.find(u => u.code === employeeCode);
                                    if (!user) {
                                        console.warn(`未找到工号为 ${employeeCode} 的用户`);
                                        continue;
                                    }

                                    const row = {
                                        id: Date.now().toString() + i,
                                        userId: user.id,
                                        employeeName: user.name,
                                        employeeCode: user.code,
                                        location: user.locatiom || '', // 注意：user-data.js中字段名为locatiom
                                        bu: user.bu || '',
                                        remarks: remarks
                                    };

                                    parsedData.push(row);
                                }

                                // 将解析的数据保存到临时变量中
                                this.parsedData = parsedData;
                                this.$message.success('Excel文件解析成功');
                            } catch (error) {
                                console.error('Excel解析错误:', error);
                                this.$message.error('Excel文件解析失败: ' + error.message);
                            }
                        };
                        reader.readAsArrayBuffer(file);
                    };
                    script.onerror = () => {
                        this.$message.error('加载Excel解析库失败');
                    };
                    document.head.appendChild(script);
                },

                startImport() {
                    if (this.uploadedFiles.length === 0) {
                        this.$message.error('请选择要导入的文件');
                        return;
                    }

                    this.isProcessing = true;
                    this.errorMessage = '';
                    this.importProgress = 0;

                    // 模拟导入过程
                    const interval = setInterval(() => {
                        this.importProgress += 10;
                        if (this.importProgress >= 100) {
                            clearInterval(interval);
                        }
                    }, 100);

                    setTimeout(() => {
                        try {
                            // 检查是否有解析的数据
                            if (!this.parsedData || this.parsedData.length === 0) {
                                throw new Error('没有解析到任何数据');
                            }

                            // 将解析的数据设置为正式数据
                            this.importData = this.parsedData;

                            // 更新表格数据
                            this.updateTableData();

                            this.$message.success('关键人员导入成功');
                            this.isProcessing = false;
                            this.importProgress = 100;

                            // 关闭弹窗
                            setTimeout(() => {
                                this.closeImportDialog();
                                this.importProgress = 0;
                                this.parsedData = []; // 清空临时数据
                                this.uploadedFiles = [];
                            }, 500);
                        } catch (error) {
                            this.errorMessage = error.message;
                            this.$message.error('导入过程中出现错误');
                            this.isProcessing = false;
                            this.importProgress = 0;
                        }
                    }, 2000);
                },

                handleSizeChange(val) {
                    this.pageSize = val;
                    this.currentPage = 1;
                    this.updateTableData();
                },

                handleCurrentChange(val) {
                    this.currentPage = val;
                    this.updateTableData();
                },

                updateTableData() {
                    // 计算总记录数
                    this.total = this.importData.length;

                    // 计算分页数据
                    const startIndex = (this.currentPage - 1) * this.pageSize;
                    const endIndex = startIndex + this.pageSize;
                    this.tableData = this.importData.slice(startIndex, endIndex);
                }

                // 注意：已移除导出数据方法
            }
        });
    </script>
</body>

</html>